﻿using System;
using System.Text;
using System.Web;
using System.IO;

namespace AutoComplete
{
    public partial class Download : System.Web.UI.Page
    {
        protected void lbtnDownload_Click(object sender, EventArgs e)
        {
            DownloadFile();
        }

        private void DownloadFile()
        {
            string filePath = Server.MapPath("~/downloadable file");
            string _DownloadableProductFileName = "AutocompleteTextBox.dll";

            FileInfo FileName = new FileInfo(filePath + "\\" + _DownloadableProductFileName);
            FileStream myFile = new FileStream(filePath + "\\" + _DownloadableProductFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            BinaryReader binaryReader = new BinaryReader(myFile);
            string lastUpdateTiemStamp = File.GetLastWriteTimeUtc(filePath).ToString("r");
            string encodedData = HttpUtility.UrlEncode(_DownloadableProductFileName, Encoding.UTF8) + lastUpdateTiemStamp;

            Response.Clear();
            Response.Buffer = false;
            Response.AddHeader("Accept-Ranges", "bytes");
            Response.AppendHeader("ETag", "\"" + encodedData + "\"");
            Response.AppendHeader("Last-Modified", lastUpdateTiemStamp);
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName.Name);
            Response.AddHeader("Content-Length", (FileName.Length).ToString());
            Response.AddHeader("Connection", "Keep-Alive");
            Response.ContentEncoding = Encoding.UTF8;

            binaryReader.BaseStream.Seek(0, SeekOrigin.Begin);

            int maxCount = (int)Math.Ceiling((FileName.Length  + 0.0) / 1024);

            for (int i = 0; i < maxCount && Response.IsClientConnected; i++)
            {
                Response.BinaryWrite(binaryReader.ReadBytes(1024));
                Response.Flush();
            }

            Response.End();
            binaryReader.Close();
            myFile.Close();
        }
    }
}